#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''eof
name:申请企业未结清贷款五级分类校验
code:Ent_UnpaidLoanClass5State_Check
tableName:
columnName:
groups:准入>企业征信校验
dependencies:IC_DSJ_2D
type:常用指标
dataSourceType:在线指标
description:
eof'''

'''
ECRUnpaidBadLoanInfo:未结清不良类贷款
Fiveclasscode：五级分类

ECRUnpaidSMLoanInfo:未结清关注类贷款
Fiveclasscode: 五级分类
'''

import sys
import json

reload(sys)
sys.setdefaultencoding('utf-8')

def Ent_UnpaidLoanClass5State_Check():
    null_type_list = ['', None, 'null', 'Null', 'NULL', '/','--','-']
    care_type = [u'关注' ,u'次级' ,u'可疑',u'损失']
    non_type=[u'正常',u'未知']
    count = []
    try:
        if EC in null_type_list:
            return u'缺失值'
        if len(EC) == 0:
            return u'缺失值'
        ecr = json.loads(EC[0]["ecr"])
        if ecr in null_type_list:
            return u'缺失值'
        if len(ecr) == 0:
            return u'缺失值'

        #未结清不良类贷款表
        if ecr.has_key('ECRUnpaidBadLoanInfo') and ecr['ECRUnpaidBadLoanInfo'] not in null_type_list:
            for i in ecr['ECRUnpaidBadLoanInfo']:
                if i.has_key('Fiveclasscode') :
                    if i['Fiveclasscode'] in care_type:
                        count.append(float(1))
                    elif i['Fiveclasscode'] in non_type:
                        count.append(float(0))
                    else:
                        count.append(None)
                else:
                    count.append(None)
        else:
            count.append(None)
        #未结清关注类贷款表
        if ecr.has_key('ECRUnpaidSMLoanInfo') and ecr['ECRUnpaidSMLoanInfo'] not in null_type_list:
            for i in ecr['ECRUnpaidSMLoanInfo']:
                if i.has_key('Fiveclasscode') :
                    if  i['Fiveclasscode'] in care_type:
                        count.append(float(1))
                    elif i['Fiveclasscode'] in non_type:
                        count.append(float(0))
                    else:
                        count.append(None)
                else:
                    count.append(None)
        else:
            count.append(None)

        # 若count均为None,则返回缺失值,否则将None置为0
        no_count = filter(lambda x: x is not None, count)
        return sum(no_count) if len(no_count) != 0 else u'缺失值'
    except:
        return u'缺失值'

result = Ent_UnpaidLoanClass5State_Check()